package com.jhd.jiangxi.activity.scan.loss;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.android.material.tabs.TabLayout;
import com.jhd.jiangxi.R;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.activity.main.BaseActivity;
import com.jhd.jiangxi.activity.scan.BillFragment;
import com.jhd.jiangxi.activity.scan.ContentFragment;
import com.jhd.jiangxi.activity.scan.DetailActivity;
import com.jhd.jiangxi.util.PopWindow;
import com.jhd.jiangxi.service.GetVaccineService;
import com.jhd.jiangxi.util.ScanUtil;
import com.jhd.jiangxi.vo.ElectCodePackageVoList;
import com.jhd.jiangxi.vo.JsonForResult;
import com.jhd.jiangxi.vo.PiatsInfo;
import com.jhd.jiangxi.vo.ScrapOrderDtlVo;
import com.jhd.jiangxi.vo.ScrapOrderMstVo;
import com.jhd.jiangxi.vo.StorageCodeVo;
import com.jhd.jiangxi.vo.VaccineCount;
import com.jhd.jiangxi.vo.VaccineInfoScrap;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/*报损*/
public class ScanLossActivity extends BaseActivity implements View.OnClickListener {

    private ViewPager vp;
    private BillFragment billFragment;
    private ContentFragment contentFragment;
    private List<Fragment> mDatas = new ArrayList<Fragment>();
    private TabLayout tabs;
    private String[] categoryName = {"国家免疫规划疫苗", "地方免疫规划疫苗", "应急接种疫苗", "非免疫规划疫苗", "群体性预防接种疫苗", "紧急使用疫苗"};
    private String[] categoryId ={"1", "4", "5", "2", "6", "7"};
    private String[] reasons={"开封过有效期","其他"};
    private FragmentPagerAdapter adapter;
    private BarcodeDataReceiver barcodeDataReceiver;
    private AlertDialog _alertDialog=null;
    private final List<String> id = new ArrayList<String>();
    private final List<String> name = new ArrayList<String>();
    List<VaccineCount> vaccineCountList = new ArrayList<>();
    private RecyclerView rvVaccine;
    private Context context=ScanLossActivity.this;
    private TextView btnLossPerson,btnSourceType_0,btnApprovalIn,btnOutDept,btnVaccineType,btnPriceBook,btnToTemp,btnStorage;//bill界面:审批人,供货单位,疫苗类型,价格本,下一步
    private Button btnSubmitVaccine,btnDelAllVaccine,btnCountVaccine;//content界面:提交,清空,入库明细
    private VaccineInfoScrap vaccineInfoScrap;
    protected static List<VaccineInfoScrap> vaccineInfoScrapList=new ArrayList<>();
    private ListView listView;
    private PopupWindow popup;private boolean isCheck=false;
    private VaccineAdapter vaccineAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_loss);
        popup = new PopupWindow(context);
        checkAllScrapOrderByCondition();
        checkAllPickOrderByCondition();
        initView();
        initEvent();
    }
    /*将顶部标题带入,新建俩个fragment*/
    private void initView() {
        initHeader("报损");
        vp = (ViewPager) findViewById(R.id.vpSheet);
        billFragment = new BillFragment();
        contentFragment = new ContentFragment();
        mDatas.add(billFragment);
        mDatas.add(contentFragment);
        tabs = findViewById(R.id.tabSheet);
    }

    @Override
    public void fragmentCreated(View view) {
        super.fragmentCreated(view);
        btnSourceType_0=(TextView)view.findViewById(R.id.btnSourceType_0);
        btnSourceType_0.setVisibility(View.GONE);//将该按钮隐藏
        btnOutDept=(TextView)view.findViewById(R.id.btnOutDept);
        btnOutDept.setVisibility(View.GONE);//将该按钮隐藏
        btnStorage=(TextView)view.findViewById(R.id.btnStorage);
        btnStorage.setVisibility(View.GONE);//将该按钮隐藏
        btnApprovalIn=(TextView)view.findViewById(R.id.btnApprovalIn);
        btnVaccineType=(TextView)view.findViewById(R.id.btnVaccineType);
        btnPriceBook=(TextView)view.findViewById(R.id.btnPriceBook);
        btnToTemp=(TextView)view.findViewById(R.id.btnToTemp);
        btnLossPerson=(TextView)view.findViewById(R.id.btnLossPerson);
        btnLossPerson.setVisibility(View.VISIBLE);
        btnLossPerson.setText(application.getRealName());
        btnApprovalIn.setOnClickListener((View.OnClickListener) context);
        btnVaccineType.setOnClickListener((View.OnClickListener) context);
        btnPriceBook.setOnClickListener((View.OnClickListener) context);
        btnToTemp.setOnClickListener((View.OnClickListener) context);
        getApproval(btnApprovalIn,"报损");//获取审批人列表
        getPriceBookMst();//获取价格本列表
    }
    @Override
    public void fragmentCreated2(View view) {
        super.fragmentCreated2(view);
        btnSubmitVaccine=(Button)view.findViewById(R.id.btnSubmitVaccine);
        btnDelAllVaccine=(Button)view.findViewById(R.id.btnDelAllVaccine);
        btnCountVaccine=(Button)view.findViewById(R.id.btnCountVaccine);
        rvVaccine=(RecyclerView)view.findViewById(R.id.rvVaccine);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        rvVaccine.setLayoutManager(layoutManager);
        btnSubmitVaccine.setOnClickListener((View.OnClickListener) context);
        btnDelAllVaccine.setOnClickListener((View.OnClickListener) context);
        btnCountVaccine.setOnClickListener((View.OnClickListener) context);
    }
    /*点击下一步或者点击扫码入库之前的判断*/
    private void setBtnToTemp(){
        if (btnApprovalIn.getText().toString().equals("审核人")||btnVaccineType.getText().toString().equals("疫苗属性")|| btnPriceBook.getText().toString().equals("价格本")) {
            UtilHelper.alertMsg(context, "请配置好单据页面", "点击任意处关闭弹窗");
            vp.setCurrentItem(0);
        } else {//调用审核领用单,审核报损单,全部返回true,才能报损
            if(isPick&&isScrap){
                vp.setCurrentItem(1);
            }else{
                vp.setCurrentItem(0);
                Toast.makeText(context,"没有报损权限!",Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void initEvent() {
        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
//                添加选中Tab的逻辑
                if (tab.getPosition() == 1) {
                    setBtnToTemp();
                } else {
                    ScanUtil.powerOffScan(context);
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
//                添加未选中Tab的逻辑
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
//                再次选中tab的逻辑
            }
        });
        adapter = new FragmentPagerAdapter(getSupportFragmentManager(),1) {
            @Override
            public int getCount() {
                return mDatas.size();
            }

            @Override
            public Fragment getItem(int position) {
                return mDatas.get(position);
            }
        };
        vp.setAdapter(adapter);
        tabs.setupWithViewPager(vp);
        TabLayout.Tab tab = tabs.getTabAt(0);
        ((View) tab.view).setBackgroundResource(R.drawable.tab_left);
        tab.setText("交货单");
        tab = tabs.getTabAt(1);
        ((View) tab.view).setBackgroundResource(R.drawable.tab_right);
        tab.setText("扫码入库");
    }

    public void openScan(Context context) {
        barcodeDataReceiver = new BarcodeDataReceiver();
        IntentFilter mFilter = new IntentFilter("nlscan.action.SCANNER_RESULT");
        context.registerReceiver(barcodeDataReceiver, mFilter);
        Intent mIntent = new Intent("ACTION_BAR_SCANCFG");
        mIntent.putExtra("SCAN_INTERVAL", Long.valueOf(3000));
        mIntent.putExtra("EXTRA_TRIG_MODE", 0);//超时扫描模式
        mIntent.putExtra("EXTRA_SCAN_MODE", 3);//广播输出模式
        context.sendBroadcast(mIntent);
        Intent mIntent2 = new Intent("ACTION_BAR_SCANCFG");
        mIntent2.putExtra("EXTRA_SCAN_NOTY_SND", 1);
        mIntent2.putExtra("EXTRA_SCAN_NOTY_VIB", 1);
        sendBroadcast(mIntent2);
    }
    public void closeScan(Context context) {
        context.unregisterReceiver(barcodeDataReceiver);
    }
    class BarcodeDataReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String scanResult_1 = intent.getStringExtra("SCAN_BARCODE1");
            final String scanStatus = intent.getStringExtra("SCAN_STATE");
            Intent stopIntent = new Intent("nlscan.action.STOP_SCAN");
            sendBroadcast(stopIntent);
            if ("ok".equals(scanStatus)) {
                if(!contains(vaccineInfoScrapList,scanResult_1)){
                    Intent mIntent2 = new Intent("ACTION_BAR_SCANCFG");
                    mIntent2.putExtra("EXTRA_SCAN_POWER", 0);
                    sendBroadcast(mIntent2);
                    getVaccineInfoByCodeForPDAScrap(scanResult_1);//index为orderType的值
                }else{
                    Toast.makeText(context,"该码已经扫描过",Toast.LENGTH_SHORT).show();
                }

            }
        }
    }
    /*重写返回键*/
    private void back(){
        if (vp.getCurrentItem() == 0) {
            onBackPressed();
        } else if (vp.getCurrentItem() == 1) {
            vp.setCurrentItem(0);//如果是在内容界面点击返回,就回到单据界面
        }
    }
    /*头部的方法,因为返回的功能要重新编写,所以直接重写*/
    protected void initHeader(String title) {
        if ("0".equals(application.getBackSystem())) title = title + "(测试版本)";
        TextView tvTitle = ((TextView) findViewById(R.id.screenTitle));
        if (tvTitle != null) tvTitle.setText(title);
        findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
        String userName = application.getRealName() == null ? application.getUserName() : application.getRealName();
        ((TextView) findViewById(R.id.tvHeaderUserName)).setText(userName);
    }

    /*重写返回方法,和initHeader一样*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /*获取报损疫苗内容*/
    protected void getVaccineInfoByCodeForPDAScrap(String code) {
        String baseUrl = UtilHelper.baseUrls.EMIAO(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(application, baseUrl);
        Map<String, String> params = ParamsMapUtil.getInstance("deptId", application.getDeptId()).addParam("code",code);
        String token = application.getAccessToken();
        Call<JsonForResult> jsonForResultCall = null;
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        jsonForResultCall = vs.getVaccineInfoByCodeForPDAScrap(token, params);
        jsonForResultCall.enqueue(new getVaccineInfoByCodeForPDAScrap());
    }

    private class getVaccineInfoByCodeForPDAScrap implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    vaccineInfoScrap = JSON.parseObject(jsonForResult.getData().toString(), VaccineInfoScrap.class);
                    dialog(vaccineInfoScrap,vaccineInfoScrapList.size()-1);//跳弹窗,选择储位,加原因和报损数
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(getApplicationContext(), "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "获取数据失败!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        }
    }

    public boolean contains(List<VaccineInfoScrap> vaccineInfoScrapList,String code) {
        for (VaccineInfoScrap infoScrap : vaccineInfoScrapList) {
            if(infoScrap.getCode().equals(code)){
                return true;
            }
        }
        return false;
    }

    private void dialog(VaccineInfoScrap vaccineInfoScrap,int position) {
        if (_alertDialog != null) {
            _alertDialog.dismiss();
        }
        LayoutInflater mLayoutInflater = LayoutInflater.from(context);
        View view = mLayoutInflater.inflate(R.layout.dialog_loss, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        _alertDialog.setCanceledOnTouchOutside(false);//setCancelable(false);返回键有效
        _alertDialog.show();
        TextView tvVaccineName = (TextView) view.findViewById(R.id.tvVaccineName);
        TextView btnStorage = (TextView) view.findViewById(R.id.btnStorage);
        EditText btnReason = (EditText) view.findViewById(R.id.btnReason);
        EditText btnLossNumber = (EditText) view.findViewById(R.id.btnLossNumber);
        TextView tvCancel = (TextView) view.findViewById(R.id.tvCancel);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        tvVaccineName.setText(vaccineInfoScrap.getVaccineName());
        btnStorage.setText(vaccineInfoScrap.getStorageCodeVoList().get(0).getStorageName());
        vaccineInfoScrap.setKc(String.valueOf(vaccineInfoScrap.getStorageCodeVoList().get(0).getQuantity()));
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent("ACTION_BAR_SCANCFG");
                mIntent.putExtra("EXTRA_SCAN_POWER", 1);//禁用扫描功能
                sendBroadcast(mIntent);
                _alertDialog.dismiss();
            }
        });
        btnReason.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show(btnReason,Arrays.asList(reasons));
            }
        });
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int lossNumber=Integer.valueOf(btnLossNumber.getText().toString().trim());
                int totalNumber=Integer.valueOf(vaccineInfoScrap.getPartQuantity())*Integer.valueOf(vaccineInfoScrap.getPkgAmount());
                if(btnReason.getText().toString().trim().equals("")||btnLossNumber.getText().toString().trim().equals("")){
                    Toast.makeText(context, "请填写报损原因和数量!", Toast.LENGTH_SHORT).show();
                }else {
                    if(lossNumber>totalNumber-vaccineInfoScrap.getPickOrderQuantity()||lossNumber<1){
                        Toast.makeText(context, "报损数不正确,请重新填写", Toast.LENGTH_SHORT).show();
                    }else{
                        vaccineInfoScrap.setReason(btnReason.getText().toString());
                        vaccineInfoScrap.setQuantity(btnLossNumber.getText().toString().trim());
                        vaccineInfoScrapList.add(vaccineInfoScrap);
                        if (vaccineInfoScrapList.size() == 1) {
                            vaccineAdapter = new VaccineAdapter(vaccineInfoScrapList);
                            rvVaccine.setAdapter(vaccineAdapter);
                        } else {
                            vaccineAdapter.notifyItemInserted(vaccineInfoScrapList.size()-1);
                            vaccineAdapter.notifyItemRangeChanged(vaccineInfoScrapList.size()-1, 1);//更新的位置,更新的总条数
                            vaccineAdapter.notifyItemRangeChanged(position, 1);//更新的位置,更新的总条数
                        }
                        Intent mIntent = new Intent("ACTION_BAR_SCANCFG");
                        mIntent.putExtra("EXTRA_SCAN_POWER", 1);//禁用扫描功能
                        sendBroadcast(mIntent);
                        _alertDialog.dismiss();
                    }
                }

            }
        });
    }

    private void saveScrapOrderMstAndDtlForPDAScrap(){
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        ScrapOrderMstVo scrapOrderMstVo = new ScrapOrderMstVo();
        scrapOrderMstVo.setApprovalId(application.getApprovalId());
        scrapOrderMstVo.setCategory(application.getCategory());
        scrapOrderMstVo.setPriceBookNo(application.getPriceNoIn());
        scrapOrderMstVo.setPriceBookMstId(application.getPriceBookMstId());
        scrapOrderMstVo.setDeptId(application.getDeptId());
        scrapOrderMstVo.setUserId(application.getUserId());
        scrapOrderMstVo.setUserName(application.getRealName());
        if(application.getRemark()==null){
            scrapOrderMstVo.setRemark("");//备注
        }else{
            scrapOrderMstVo.setRemark(application.getRemark());//备注
        }
        List<ScrapOrderDtlVo> scrapOrderDtlVos = new ArrayList<ScrapOrderDtlVo>();

        DecimalFormat df = new DecimalFormat("0.00");
        for (int i = 0; i < vaccineInfoScrapList.size(); i++) {
            ScrapOrderDtlVo scrapOrderDtlVo = new ScrapOrderDtlVo();
            scrapOrderDtlVo.setCategory(vaccineInfoScrapList.get(i).getCategory());
            ElectCodePackageVoList electCodePackageVoList = new ElectCodePackageVoList();
            electCodePackageVoList.setCodeLevel(vaccineInfoScrapList.get(i).getCodeLevel());
            electCodePackageVoList.setElectCode(vaccineInfoScrapList.get(i).getCode());
            electCodePackageVoList.setQuantity(df.format((float)Integer.valueOf(vaccineInfoScrapList.get(i).getQuantity())/Integer.valueOf(vaccineInfoScrap.getPartQuantity())));
            scrapOrderDtlVo.setElectCodePackageVoList(electCodePackageVoList);
            scrapOrderDtlVo.setExpiryDate(vaccineInfoScrapList.get(i).getExpiryDate());
            scrapOrderDtlVo.setLotNumber(vaccineInfoScrapList.get(i).getLotNumber());
            scrapOrderDtlVo.setManufacturerId(vaccineInfoScrapList.get(i).getManufacturerId());
            scrapOrderDtlVo.setManufacturerName(vaccineInfoScrapList.get(i).getManufacturerName());
            scrapOrderDtlVo.setPropertyId(vaccineInfoScrapList.get(i).getPropertyId());
            scrapOrderDtlVo.setQuantity(df.format((float)Integer.valueOf(vaccineInfoScrapList.get(i).getQuantity())/Integer.valueOf(vaccineInfoScrap.getPartQuantity())));
            scrapOrderDtlVo.setReason(vaccineInfoScrapList.get(i).getReason());
            scrapOrderDtlVo.setStorage(vaccineInfoScrapList.get(i).getStorageCodeVoList().get(0).getStorageName());
            scrapOrderDtlVo.setStorageId(vaccineInfoScrapList.get(i).getStorageCodeVoList().get(0).getStorageId());
            scrapOrderDtlVo.setVaccineId(vaccineInfoScrapList.get(i).getVaccineId());
            scrapOrderDtlVo.setVaccineName(vaccineInfoScrapList.get(i).getVaccineName());
            scrapOrderDtlVo.setVaccineLotsId(vaccineInfoScrapList.get(i).getVaccineLotsId());
            scrapOrderDtlVos.add(scrapOrderDtlVo);
        }
        params.put("scrapOrderDtlVoList", scrapOrderDtlVos);
        params.put("scrapOrderMstVo", scrapOrderMstVo);
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.EMIAO(application.getBackSystem()));
        GetVaccineService vs = retrofit.create(GetVaccineService.class);
        String token = application.getAccessToken();
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
        Call<JsonForResult> jsonForResultCall = vs.saveScrapOrderMstAndDtlForPDAScrap(token, requestBody);
        jsonForResultCall.enqueue(new saveScrapOrderMstAndDtlForPDAScrap());
    }
    private class saveScrapOrderMstAndDtlForPDAScrap implements Callback<JsonForResult> {

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    Toast.makeText(context, "报损成功", Toast.LENGTH_SHORT).show();
                    onBackPressed();
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null && "".equals(jsonForResult.getMessage()) == false) {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "网络异常!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(context, "错误", msg);
        }
    }

    /*button的点击监听*/
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnToTemp:
                vp.setCurrentItem(1);
                break;
            case R.id.btnApprovalIn://bill界面点击选择审批人
                name.clear();
                id.clear();
                if(approvalList!=null){
                    for (int i = 0; i < approvalList.size(); i++) {
                        name.add(approvalList.get(i).getUserName1());
                        id.add(approvalList.get(i).getId());
                    }
                    PopWindow.show(application,context,popup,isCheck,(TextView)v,name,id,0);
                }else{
                    Toast.makeText(context,"未获取审批人信息,请稍后重试!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnVaccineType://bill界面点击选择疫苗类型btnVaccineType
                v.setBackgroundResource(R.drawable.selector_focused);
                List<String> categoryNames= Arrays.asList(categoryName);
                List<String> categoryIds= Arrays.asList(categoryId);
                PopWindow.show(application,context,popup,isCheck,(TextView) v,categoryNames,categoryIds,2);
                break;
            case R.id.btnPriceBook://bill界面点击选择价格本
                name.clear();
                id.clear();
                if(priceBook!=null){
                    for (int i = 0; i < priceBook.size(); i++) {
                        name.add(priceBook.get(i).getPriceBookNo());
                        id.add(priceBook.get(i).getId());
                    }
                    PopWindow.show(application,context,popup,isCheck,(TextView) v,name,id,3);
                }else{
                    Toast.makeText(context,"未获取价格本信息,请稍后重试!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btnSubmitVaccine://content界面点击保存扫描疫苗
                showDialog(1,v,"确认提交");
                break;
            case R.id.btnDelAllVaccine://content界面点击删除所有扫到的疫苗
                showDialog(2,v,"清空扫描");
                break;
            case R.id.btnCountVaccine://content界面点击跳转到汇总界面
                Intent stopIntent = new Intent("nlscan.action.STOP_SCAN");
                sendBroadcast(stopIntent);
                startActivity(new Intent(context, LossDetailActivity.class));
                break;
        }
    }
    public void showDialog(int dex, View v, String title) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(v.getContext());
        alertBuilder.setTitle(title);
        if (title.equals("确认提交")) {
            String msg = "";
            vaccineCountList.clear();
            for (VaccineInfoScrap vaccineInfoScrap : vaccineInfoScrapList) {
                VaccineCount vaccineCount=new VaccineCount();
                vaccineCount.setName(vaccineInfoScrap.getVaccineName());
                if(!vaccineCountList.contains(vaccineCount)){
                    vaccineCountList.add(vaccineCount);
                }
            }
            for (VaccineCount vaccineCount : vaccineCountList) {
                int num=0;
                for (VaccineInfoScrap vaccineInfoScrap : vaccineInfoScrapList) {
                    if(vaccineInfoScrap.getVaccineName().equals(vaccineCount.getName())){
                        num=num+Integer.valueOf(vaccineInfoScrap.getQuantity());
                    }
                }
                vaccineCount.setNum(num);
            }
            for (int i = 0; i < vaccineCountList.size(); i++) {
                msg =msg+ "疫苗名称:" + vaccineCountList.get(i).getName() + " 报损数:" + vaccineCountList.get(i).getNum() + "\n";
            }
            alertBuilder.setMessage("已扫疫苗 " + msg + "你确定报损吗?");
        } else if (title.equals("清空扫描")) {
            alertBuilder.setIcon(R.mipmap.dialog_alert);
            alertBuilder.setMessage("你确定清空所有扫描疫苗吗");
        }
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (dex == 1) {//保存所有数据
                    saveScrapOrderMstAndDtlForPDAScrap();
                } else if (dex == 2) {//清空储位数据
                    vaccineInfoScrapList.clear();
                    VaccineAdapter vaccineAdapter = new VaccineAdapter(vaccineInfoScrapList);
                    rvVaccine.setAdapter(vaccineAdapter);
                }
                _alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                _alertDialog.dismiss();
            }
        });
        _alertDialog = alertBuilder.create();
        _alertDialog.show();
    }
    private void show(EditText editText, List<String> name) {
        isCheck=false;
        listView = new ListView(context);
        listView.setDivider(null);//设置分割线
        listView.setVerticalScrollBarEnabled(false);//不显示滑动条
        listView.setAdapter(new MyAdapter(editText,name));
        if(popup.isShowing())popup.dismiss();
        popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popup.setWidth(editText.getWidth());
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.selector_unfocused));
        popup.setContentView(listView);//设置显示内容
        popup.setOutsideTouchable(true);//点击PopupWindow以外的区域自动关闭该窗口
        popup.showAsDropDown(editText, 0, 5);//显示在edit控件的下面0,0代表偏移量
        editText.setBackgroundResource(R.drawable.selector_focused);
        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                editText.setBackgroundResource(R.drawable.selector_unfocused);
            }
        });
    }

    //适配器
    private class MyAdapter extends BaseAdapter {
        private List<String> name;private EditText editText;

        public MyAdapter(EditText editText,List<String> name) {
            this.name = name;
            this.editText = editText;
        }

        @Override
        public int getCount() {
            return name.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HolderView holderView = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_dialog_login, null);
                holderView = new HolderView();
                holderView.text = (TextView) convertView.findViewById(R.id.tvStorage);
                convertView.setTag(holderView);
            } else {
                holderView = (HolderView) convertView.getTag();
            }

            holderView.text.setText(name.get(position));

            holderView.text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!name.get(position).equals("其他")){editText.setText(name.get(position));}
                    editText.setTextColor(getResources().getColor(R.color.billTextChoose));
                    notifyDataSetChanged();
                    editText.setBackgroundResource(R.drawable.selector_unfocused);
                    popup.dismiss();
                }
            });
            return convertView;
        }
    }

    public class HolderView {//由于这里用户都是同一个人,就省略用户图像的刷新
        private TextView text;
    }
    public class VaccineAdapter extends RecyclerView.Adapter<VaccineAdapter.ViewHolder> {
        private List<VaccineInfoScrap> vaccineInfoScrapList;

        public VaccineAdapter(List<VaccineInfoScrap> vaccineInfoScrapList) {
            this.vaccineInfoScrapList = vaccineInfoScrapList;
        }

        @NonNull
        @Override
        public VaccineAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vaccine_loss, parent, false);
            VaccineAdapter.ViewHolder viewHolder = new VaccineAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull VaccineAdapter.ViewHolder holder, int position) {
            holder.tv_electCode.setText(vaccineInfoScrapList.get(position).getCode());
            holder.tvVaccineName.setText(vaccineInfoScrapList.get(position).getVaccineName());
            holder.tvFactory.setText(vaccineInfoScrapList.get(position).getManufacturerName());
            holder.tvApprovalNo.setText(vaccineInfoScrapList.get(position).getLotNumber());
            holder.tvVaccineDose.setText(vaccineInfoScrapList.get(position).getVaccineDose() + "/" + vaccineInfoScrapList.get(position).getVaccineSpec());
            holder.tvCodeLevelStr.setText(vaccineInfoScrapList.get(position).getCodeLevelStr());
            holder.tvExpireDate.setText(vaccineInfoScrapList.get(position).getExpiryDate());
            holder.tvStorage.setText(vaccineInfoScrapList.get(position).getStorageCodeVoList().get(0).getStorageName());
            holder.tvPersonQuantity.setText(vaccineInfoScrapList.get(position).getQuantity());
            holder.tvReason.setText(vaccineInfoScrapList.get(position).getReason());
            holder.tvStorageCount.setText(vaccineInfoScrapList.get(position).getKc());
            if (vaccineInfoScrapList.get(position).getCategory().equals("1")) {
                holder.iv_category.setText("免规");
            }else if(vaccineInfoScrapList.get(position).getCategory().equals("4")){
                holder.iv_category.setText("地方免规");
            }else if(vaccineInfoScrapList.get(position).getCategory().equals("5")){
                holder.iv_category.setText("应急");
            }else if(vaccineInfoScrapList.get(position).getCategory().equals("2")){
                holder.iv_category.setText("非免规");
            }else if(vaccineInfoScrapList.get(position).getCategory().equals("6")){
                holder.iv_category.setText("群体性预防");
            }else if(vaccineInfoScrapList.get(position).getCategory().equals("7")){
                holder.iv_category.setText("紧急");
            }
            holder.iv_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    vaccineInfoScrapList.remove(position);
                    notifyItemRemoved(position);//移除该位置的项目
                    notifyItemRangeChanged(position, getItemCount() - position);//局部刷新从该position位置开始到剩余的所有项目
                }
            });
            //跳弹窗,选择储位
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog(vaccineInfoScrapList.get(position), position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return vaccineInfoScrapList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_electCode, tvVaccineName, tvFactory, tvApprovalNo,tvStorageCount,tvReason,iv_category; //追溯码,疫苗名称，生产厂家，批号,库存,原因,疫苗属性
            TextView tvVaccineDose, tvCodeLevelStr, tvExpireDate, tvStorage,tvPersonQuantity; // 计量规格,包装类型,效期,储位
            ImageView iv_del;
            LinearLayout linearLayout;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_electCode = itemView.findViewById(R.id.tv_electCode);
                this.tvVaccineName = itemView.findViewById(R.id.tvVaccineName);
                this.iv_del = itemView.findViewById(R.id.iv_del);
                this.iv_category = itemView.findViewById(R.id.iv_category);
                this.tvFactory = itemView.findViewById(R.id.tvFactory);
                this.tvApprovalNo = itemView.findViewById(R.id.tvApprovalNo);
                this.tvVaccineDose = itemView.findViewById(R.id.tvVaccineDose);
                this.tvCodeLevelStr = itemView.findViewById(R.id.tvCodeLevelStr);
                this.tvExpireDate = itemView.findViewById(R.id.tvExpireDate);
                this.tvStorageCount = itemView.findViewById(R.id.tvStorageCount);
                this.tvStorage = itemView.findViewById(R.id.tvStorage);
                this.tvReason = itemView.findViewById(R.id.tvReason);
                this.tvPersonQuantity = itemView.findViewById(R.id.tvPersonQuantity);
                this.linearLayout = itemView.findViewById(R.id.linearLayout);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        vaccineInfoScrapList.clear();
        application.clearBill();
    }
}